package billingServer;

import java.io.IOException;
import java.io.InputStream;
import java.rmi.NoSuchObjectException;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Group 95
 */
public class BillingServerRMI extends UnicastRemoteObject implements IBillingServerRMI {

    private IBillingServerSecure secureServer;
    private Properties users;

    public BillingServerRMI() throws RemoteException, Exception {
        super();
        loadUsers();
        secureServer = new BillingServerSecure();
    }

    public void stop() {
            if (secureServer != null) {
            try {
                UnicastRemoteObject.unexportObject(secureServer, true);
            } catch (NoSuchObjectException ex) {
                Logger.getLogger(BillingServerRMI.class.getName()).log(Level.SEVERE, null, ex);
            }
                secureServer = null;
                
            }
    }

    public void loadUsers() throws Exception {
        InputStream is = ClassLoader.getSystemResourceAsStream("user.properties");
        if (is != null) {
            users = new java.util.Properties();
            try {
                users.load(is);
            } catch (IOException iox) {
                Logger.getLogger(BillingServerRMI.class.getName()).log(Level.SEVERE, null, iox);
                throw new Exception("Error while reading Properties file");
            } finally {
                try {
                    is.close();
                } catch (IOException ex) {
                    //ignore
                }
            }
        } else {
            Logger.getLogger(BillingServerRMI.class.getName()).log(Level.SEVERE, "Properties file not found!");
            throw new Exception("Properties file not found!");
        }
    }

    @Override
    public IBillingServerSecure login(String username, String password) throws RemoteException {
        //@todo ev. checken ob user schon eingeloggt.
        if (users != null && password != null && password.equals(users.getProperty(username))) {
            return this.secureServer;
        }
        return null;
    }
}
